<template>
    <div>
        <div class="top">
            <el-button type="primary" @click="addgoods">新建</el-button>
            <el-button type="primary" @click="refresh">刷新</el-button>
        </div>
        <!-- 员工表格 -->
        <div style="height: 70vh;">
            <el-table ref="multipleTable" :data="employlist" tooltip-effect="dark" class="my-4"
                style="width: 100%;height:100%;" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="id" label="员工ID" width="80" />
                <el-table-column label="头像" width="180">
                    <template #default="scope">
                        <!-- <img v-if="avatar" :src="avatar" alt=""> -->
                        <el-avatar v-if="scope.row.avatar != ''" :src="scope.row.avatar"></el-avatar>
                        <el-avatar v-else>
                            <el-icon :size="24">
                                <UserFilled />
                            </el-icon>
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column prop="realname" label="员工名称" width="180" />
                <el-table-column prop="username" label="用户名" width="180" />
                <el-table-column prop="role" label="员工职位"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" @click="editrow(scope)">编辑</el-button>
                        <!-- <el-button type="danger" @click="deleterow(scope)">删除</el-button> -->
                        <el-popconfirm title="确定删除吗?" icon="null" confirmButtonType="danger" confirmButtonText="确定"
                            cancelButtonText="取消" @confirm="deleterow(scope)">
                            <template #reference>
                                <el-button type="danger" v-loading.fullscreen.lock="fullscreenLoading">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-button type="primary" @click="deleteselect"
                    v-loading.fullscreen.lock="fullscreenLoading">删除选择</el-button>
            </div>
        </div>
        <!-- 新建弹出框 -->
        <el-dialog title="新建员工信息" v-model="dialogVisible" width="40%" :before-close="handleClose">
            <el-form label-position="top" :model="employ">
                <el-form-item label="头像:">
                    <el-upload action="" :http-request="UploadImage" multiple :limit="1" name="files"
                        accept="image/jpeg,image/png" list-type="picture-card" :on-preview="addhandlePictureCardPreview"
                        :on-remove="handleRemove" :before-upload="onBeforeUpload">
                        <el-icon :size="size" :color="color">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog style="width: 400px; heigth: 400px" v-model="pohots">
                        <img style="width: 100%;" :src="employ.avatar" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="用户名:">
                    <el-input v-model="employ.username" clearable></el-input>
                </el-form-item>
                <el-form-item label="密码:">
                    <el-input type="password" v-model="employ.password" clearable show-password></el-input>
                </el-form-item>
                <el-form-item label="员工名称:">
                    <el-input v-model="employ.realname" clearable></el-input>
                </el-form-item>
                <el-form-item label="员工职位:">
                    <el-select v-model="employ.role" placeholder="请选择">
                        <el-option v-for="item in roleoptions" :key="item.value" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="sureadd" v-loading.fullscreen.lock="fullscreenLoading">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑弹出框 -->
        <el-dialog title="编辑员工信息" v-model="updateVisible" width="40%" :before-close="handleClose">
            <el-form label-position="top" :model="employ">
                <el-form-item label="头像:">
                    <el-upload action="" :http-request="EitdImage" multiple :limit="1" name="files"
                        accept="image/jpeg,image/png" list-type="picture-card" :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove" :before-upload="onBeforeUpload">
                        <el-icon :size="size" :color="color">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog style="width: 400px; heigth: 400px" v-model="updatePohots">
                        <img style="width: 100%;" :src="updateemployinfo.avatar" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="员工名称:">
                    <el-input v-model="updateemployinfo.realname" clearable></el-input>
                </el-form-item>
                <el-form-item label="员工职位:">
                    <el-select v-model="updateemployinfo.role" placeholder="请选择">
                        <el-option v-for="item in roleoptions" :key="item.value" :label="item.label" :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="密码:">
                    <el-input type="password" v-model="updateemployinfo.password" clearable show-password></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateVisible = false">取 消</el-button>
                    <el-button type="primary" @click="sureupdate" v-loading.fullscreen.lock="fullscreenLoading">确
                        定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { selectemploy, addemploy, deleteemploy, updateemploy, deletemoreemploy } from '../../../../api/employapi'
import Format from '../../../../api/uploadimg'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, Plus } from '@element-plus/icons-vue'


let dialogVisible = ref(false)  //新建弹出框
let pohots = ref(false)  //上传图片后显示
let updatePohots = ref(false)
let fileObj = ref([])    //上传的图片文件
let issame = ref(false)   //是否有相同用户名
let deleteArrs = ref([])  //删除多条员工信息id数组
let updateVisible = ref(false)  //编辑弹出框
let fullscreenLoading = ref(false)  //加载显示
let employ = ref({ avatar: '', username: '', password: '', realrealname: '', role: '' })  //新建员工参数
let updateemployinfo = ref({ id: '', avatar: '', realrealname: '', role: '', password: '' })  //编辑员工参数
let employlist = ref([])   //商品列表
let roleoptions = ref([
    {
        value: '1',
        label: '管理员',
    },
    {
        value: '2',
        label: '普通员工',
    },
    {
        value: '3',
        label: '销售员',
    }
])

//查询所有员工
const getemploylist = (refresh) => {
    selectemploy().then(res => {
        if (res.data.data.code == 200) {
            employlist.value = res.data.data.employlist
            if (refresh) {
                ElMessage.success("刷新成功")
            }
        } else {
            ElMessage.error(res.data.data.msg)
            if (refresh) {
                ElMessage.error("刷新失败")
            }
        }
    })

}
getemploylist()



//点击新建
const addgoods = () => {
    dialogVisible.value = true
}
//点击新建框X
const handleClose = () => {
    dialogVisible.value = false
}
//点击确认新建
const sureadd = () => {
    employlist.value.map(item => {
        if (item.username == employ.value.username) {
            issame.value = false  //有相同的
            return
        } else {
            issame.value = true  //无相同的
        }
    })
    fullscreenLoading.value = true
    setTimeout(() => {
        if (issame.value) {
            let data = {
                avatar: employ.value.avatar,
                username: employ.value.username,
                password: employ.value.password,
                realname: employ.value.realname,
                role: employ.value.role
            }
            addemploy(data).then(res => {
                if (res.data.data.code == 200) {
                    ElMessage.success(res.data.data.msg)
                    getemploylist()
                } else {
                    ElMessage.error(res.data.data.msg)
                }
                dialogVisible.value = false
                fullscreenLoading.value = false
            })
        } else {
            ElMessage.error("该用户名已存在!")
            fullscreenLoading.value = false
        }
    }, 1000)

}
//刷新
const refresh = () => {
    let refresh = ref(true)
    getemploylist(refresh)
}

//点击删除上传的图片
const handleRemove = (file, fileList) => {
    console.log(file, fileList)
    employ.value.avatar = ''
}

//点击放大图片
const addhandlePictureCardPreview = (file) => {
    console.log(file);
    pohots.value = true
}

//上传前的操作
const onBeforeUpload = (file) => {
    const isIMAGE = file.type === 'image/jpeg' || 'image/png';
    const isLt1M = file.size / 1024 / 1024 < 5;

    if (!isIMAGE) {
        ElMessage.error('上传文件只能是图片格式!');
    }
    if (!isLt1M) {
        ElMessage.error('上传文件大小不能超过 5MB!');
    }
    return isIMAGE && isLt1M;
}

//点击上传文件
const UploadImage = (files) => {
    fileObj.value = files.file;
    // 创建文件流
    let formData = new FormData();
    formData.append('files', fileObj.value);
    // Format封装在utilsg工具函数中
    Format.fileUploader(formData, '/uploading').then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success("上传成功!")
            employ.value.avatar = res.data.data.imgurl
            console.log(employ.value.avatar);
        } else {
            ElMessage.error("上传失败!")
        }
    })
}
//选中的数组
const handleSelectionChange = (val) => {
    if (val.length > 0) {
        val.map(item => {
            deleteArrs.value.push(item.id)
        })
    } else {
        deleteArrs.value = []
    }
}


//点击编辑
const editrow = (scope) => {
    updateVisible.value = true
    updateemployinfo.value.id = employlist.value[scope.$index].id
    updateemployinfo.value.avatar = employlist.value[scope.$index].avatar
    updateemployinfo.value.realname = employlist.value[scope.$index].realname
    updateemployinfo.value.role = employlist.value[scope.$index].role
    updateemployinfo.value.password = employlist.value[scope.$index].password
}

//编辑确认上传后
const handlePictureCardPreview = (file) => {
    console.log(file);
    updatePohots.value = true
}

//编辑上传图片
const EitdImage = (files) => {
    fileObj.value = files.file;
    // 创建文件流
    let formData = new FormData();
    formData.append('files', fileObj.value);
    // Format封装在utilsg工具函数中
    Format.fileUploader(formData, '/uploading').then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success("上传成功!")
            updateemployinfo.value.avatar = res.data.data.imgurl
        }
    })
}

//点击编辑确认
const sureupdate = () => {
    employlist.value.map(item => {
        if (item.username == employ.value.username) {
            issame.value = false  //有相同的
            return
        } else {
            issame.value = true  //无相同的
        }
    })
    fullscreenLoading.value = true
    setTimeout(() => {
        if (issame.value) {
            let data = {
                avatar: updateemployinfo.value.avatar,
                realname: updateemployinfo.value.realname,
                role: updateemployinfo.value.role,
                password: updateemployinfo.value.password,
                id: updateemployinfo.value.id
            }
            updateemploy(data).then(res => {
                if (res.data.data.code == 200) {
                    ElMessage.success(res.data.data.msg)
                    getemploylist()
                }
                else {
                    ElMessage.error(res.data.data.msg)
                }
                fullscreenLoading.value = false
                updateVisible.value = false

            })
        }
        else {
            ElMessage.error("该用户名已存在!")
            fullscreenLoading.value = false
        }
    }, 1000)

}

//点击删除
const deleterow = (scope) => {
    fullscreenLoading.value = true
    let data = {
        id: employlist.value[scope.$index].id
    }
    deleteemploy(data).then(res => {
        if (res.data.data.code == 200) {
            ElMessage.success(res.data.data.msg)
            getemploylist()
        }
        else {
            ElMessage.error(res.data.data.msg)
        }
        fullscreenLoading.value = false
    })
}
//点击删除选择
const deleteselect = () => {
    if (deleteArrs.value.length > 0) {
        ElMessageBox.confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            let data = deleteArrs.value
            deletemoreemploy(data).then(res => {
                console.log(res);
                if (res.data.data.code == 200) {
                    ElMessage.success(res.data.data.msg)
                    deleteArrs.value = []
                    getemploylist()
                }
                else {
                    ElMessage.error(res.data.data.msg)
                }
            })
        }).catch(() => {

        })
    } else {
        ElMessage.error('请勾选需要删除的员工信息')
    }

}


</script>